#Copyright (c) 2025, Alibaba Cloud and its affiliates;
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at

#   http://www.apache.org/licenses/LICENSE-2.0

#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.



# -*- coding: UTF-8 -*-
import random
import os
import crypt
import subprocess
import time
import json
import math
import string

from flask import current_app as app
from flask import request
from hmac import compare_digest as compare_hash
from common_libs.operate_logging import logging_opt

def genid(len):
    random_str = 'qwertyuiopasdfghjklzxcvbnm0123456789'
    str = ""
    for i in range(len):
        str = str + random_str[random.randint(0, 35)]
    return str


def iteritems(d, **kw):
    return iter(d.items(**kw))


def find_data_by_key(data, key, value):
    for i in range(len(data)):
        d = data[i]
        if d[key] != None and d[key] == value:
            return d
    return None


def pagination_data(data, offset):
    ret = []
    for index in range(len(data)):
      page = math.ceil((index+1)/offset)
      if len(ret) < page:
        ret.append([])
      ret[page-1].append(data[index])
    return ret


def get_request_data(form_key, default_value=""):
    if request.method == 'GET':
        request_form_data = request.args.get(form_key, default_value)
    else:
        request_form_data = request.form.get(form_key, default_value)
    return request_form_data


def error_handler(e):
    request_id = get_request_data('RequestId', '')
    if request.method == 'GET':
        request_form_data = request.args
    else:
        request_form_data = request.form
    # print("c",type(e))
    error_message = 'RequestID:%s Data:%s Error:%s' % (
        request_id, json.dumps(request_form_data), e)
    app.logger.error(error_message)


def get_unix_time(dt):
    get_unix_time = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))
    return get_unix_time


def run_cmd(command, time = 1):
    ret = subprocess.run(command, shell=True, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE, encoding="utf-8", timeout=time)
    if ret.returncode == 0:
        return ret.stdout
    else:
        return None

def getFileNameBySuffix(path, suffix):
    file = ''
    for f in os.listdir(path):
        if os.path.splitext(f)[1] == suffix:
            file = f
            break;
    return file

def check_passwd(passwd, cryoty_hash):
    return compare_hash(crypt.crypt(passwd, cryoty_hash), cryoty_hash)
  
def create_unix_passwd(passwd):
    randomSalt = ''.join(random.sample(string.ascii_letters,8))
    return crypt.crypt(passwd, '$6$%s$' % randomSalt)

def response_data(succeed, data, code="OK", opt_msg="success"):
    request_id = get_request_data('RequestId', '')
    if data != None:
        data["RequestId"] = request_id
    if succeed:
        logging_opt("info", opt_msg)
        return {"result": 'Succeed', "message": {"code": code, "data": data}}
    else:
        logging_opt("error", data)
        return {"result": 'Failed', "message": {"code": code, "data": data}}
